package cn.uncode.springcloud.starter.canary.ribbon.support;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * The Ribbon context holder.
 *
 * @author juny
 */
public class RibbonContextHolder {
	
	public static final Map<String, Set<String>> FLAG_TO_APP_NAME = new HashMap<>();
	
    /**
     * Stores the Ribbon context for current thread.
     */
    private static final ThreadLocal<RibbonContext> contextHolder = new InheritableThreadLocal<RibbonContext>() {
        @Override
        protected RibbonContext initialValue() {
            return new RibbonContext();
        }
    };

    /**
     * Retrieves the current thread bound instance of Ribbon context.
     *
     * @return the current context
     */
    public static RibbonContext getCurrentContext() {
        return contextHolder.get();
    }
    
    public static void setRibbonContext(RibbonContext ribbonContext) {
    	contextHolder.set(ribbonContext);   
    }

    /**
     * Clears the current context.
     */
    public static void clearCurrentContext() {
        contextHolder.remove();
    }
    
    public static void addFlag2AppName(String flag, String appName) {
    	if(FLAG_TO_APP_NAME.containsKey(flag)) {
    		FLAG_TO_APP_NAME.get(flag).add(appName);
    	}else {
    		Set<String> set = new HashSet<>();
    		set.add(appName);
    		FLAG_TO_APP_NAME.put(flag, set);
    	}
    }
    
    public static Set<String> getAppNameByFlag(String flag) {
    	return FLAG_TO_APP_NAME.get(flag);
    }
}
